package com.hutao.example.wardemo.file;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class DownloadServlet extends HttpServlet {

    // 与上传 Servlet 使用相同的目录
    private static final String UPLOAD_DIR = "D:/uploadFiles/";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 获取要下载的文件名
//        String fileName = request.getParameter("filename");
        String fileName = "app-debug.apk";
        if (fileName == null || fileName.trim().isEmpty()) {
            response.getWriter().write("Error: 文件名不能为空！");
            return;
        }

        // 安全检查：防止路径穿越攻击 (非常重要！)
        // 确保文件名中不包含 ".." 等危险字符
        if (fileName.contains("..") || fileName.contains("/") || fileName.contains("\\")) {
            response.getWriter().write("Error: 无效的文件名！");
            return;
        }

        // 2. 构建文件对象
        File file = new File(UPLOAD_DIR + fileName);

        // 3. 检查文件是否存在
        if (!file.exists() || !file.canRead()) {
            response.getWriter().write("Error: 文件不存在或无法读取！");
            return;
        }

        // 4. 设置响应头，告诉浏览器这是一个下载文件
        response.setContentType("application/octet-stream");
        // 处理中文文件名乱码问题
        String userAgent = request.getHeader("User-Agent");
        if (userAgent != null && (userAgent.contains("MSIE") || userAgent.contains("Trident"))) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        // "attachment;" 表示强制下载，而不是在浏览器中打开
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.setContentLength((int) file.length());

        // 5. 读取文件并写入响应流
        try {
            InputStream in = new FileInputStream(file);
            OutputStream out = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            // 确保缓冲区的数据被发送
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
